﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using DAL;
using BOL;
using WebLib;
using System.Data;
using System.Data.Linq;
using System.Data.SqlClient;
using Website.Logger;
using System.IO;
using System.Web.Script.Services;
using System.Web.Services;
using AjaxControlToolkit;
using UtilityExtensions;

namespace UILGestion.Seguridad
{
    public partial class RolInsertForm : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {


                if (!Page.IsPostBack)
                {
                    type.Value = (string)Request.QueryString["type"];
                    internalid.Value = (string)Request.QueryString["id"];
                    menuCtrl1.loadMenuSeguridad();
                    formatForm();



                }


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        private void loadRol()
        {





            var rolInfo = DbUtil.Db.Rols.Single(p=>p.idInternal== int.Parse(internalid.Value));

            descripcionTextBox.Text = rolInfo.descripcion;
            nivelPresupuestoDropDownList.SelectedValue = rolInfo.nivelPrespuesto.ToString();
            nivelComparativoDropDownList.SelectedValue = rolInfo.nivelComparativo.ToString();
            AprobarOCCheckBox.Checked = rolInfo.bitAprobarOrdenCompra;
            montoTextBox.Text = rolInfo.montoComparativo.ToString();
                

                //--------rendicion----
                bitAprobarCheckBox.Checked = rolInfo.bitAprobarRecepcion;
                bitVistoBuenoCajaChicachk.Checked = rolInfo.bitRevisorRecepcion;
                bitDepositoCajaChicaCheckBox.Checked = rolInfo.bitDepositoRendicionC;
                //------------Kardex-----
                bitkardexCHK.Checked = rolInfo.bitAperturaKardex;
                
                validacom2();

        }
        private void formatForm()
        {
            
            
            
            //varibles de grillas
            idFormularioRolList.Value = Parametros.GenerarID().ToString();
            
            formularioid.Value = Parametros.GenerarID().ToString();
            //inicializamos valores
            
            ShowComboBox();
            DataSet ds = new DataSet();

            if (type.Value == "E")
            {
                loadRol();
                DataTable dt = 
                    Util.EntidadToDataTable((new RolBL().getRolFormTransaccion(int.Parse(internalid.Value))));
                DataTable dt2 =
                    Util.EntidadToDataTable((new RolBL().getRolFormLista(int.Parse(internalid.Value))));

                dt.TableName = "rolFormularioListInfo";
                dt2.TableName = "rolFormularioListInfo2";
                ds.Tables.Add(dt);
                ds.Tables.Add(dt2);
                ds.AcceptChanges();
            }
            else
            {
                DataTable dt = Util.EntidadToDataTable((new RolBL().getInsertRolFormTransaccion()));
                DataTable dt2 = Util.EntidadToDataTable((new RolBL().getInsertRolFormLista()));
                dt.TableName = "rolFormularioListInfo";
                dt2.TableName = "rolFormularioListInfo2";
                ds.Tables.Add(dt);
                ds.Tables.Add(dt2);
            }
            
            Session[idFormularioRolList.Value]=ds;

            
            DataBindFormularios();
            DataBindFormulariosListas();

        }
        private void ShowComboBox()
        {
           
            //List<Obra> eFormularios = new List<Obra>();
            //using (dbGestionDataContext _db = new dbGestionDataContext(Parametros.strConnString))
            //{
            //    var q = _db.Rol;
            //    var o = from a in _db.Obras
            //            select a;
            //    //select new Obra
            //    //{
            //    //    idInternal = a.idInternal,
            //    //    descripcion = a.Proyecto.Empresa.descripcion.ToString() + "-" + a.descripcion.ToString()
            //    //};

            //    Obra cero = new Obra();
            //    cero.idInternal = 0;
            //    cero.descripcion = "-----Seleccione Obra-----";
            //    eFormularios.Add(cero);

            //    Rol rol = new Rol();
            //    cero.idInternal = 0;
            //    cero.descripcion = "----Seleccione Rol-------";
            //    eRoles.Add(rol);

            //    eRoles.AddRange(q.ToList());
            //    eFormularios.AddRange(o.ToList());
            //}
            //Session[Formulariosid.Value] = eFormularios;
            //Session[rolesid.Value] = eRoles;

        }
      
        private void DataBindFormularios()
        {
            DataSet eObraList = (DataSet)Session[idFormularioRolList.Value];
            
            formularioGridView.DataSource = eObraList.Tables["rolFormularioListInfo"];
            formularioGridView.DataBind();


            if (formularioGridView.Rows.Count == 0)
            {
                // agregamos un registro debido al footer
                rolFormularioListInfo drwcero = new rolFormularioListInfo();
                List<rolFormularioListInfo> drw = new List<rolFormularioListInfo>();
                drw.Add(drwcero);
                formularioGridView.DataSource = drw;
                formularioGridView.DataBind();
                formularioGridView.Rows[0].Visible = false;
            }

            forumlarioUpdatePanel.Update();
        }
        private void DataBindFormulariosListas()
        {
            DataSet eObraList = (DataSet)Session[idFormularioRolList.Value];

            ListaGridView.DataSource = eObraList.Tables["rolFormularioListInfo2"];
            ListaGridView.DataBind();


            if (formularioGridView.Rows.Count == 0)
            {
                // agregamos un registro debido al footer
                rolFormularioListInfo drwcero = new rolFormularioListInfo();
                List<rolFormularioListInfo> drw = new List<rolFormularioListInfo>();
                drw.Add(drwcero);
                ListaGridView.DataSource = drw;
                ListaGridView.DataBind();
                ListaGridView.Rows[0].Visible = false;
            }

            UpdatePanel12.Update();
        }

        private void setEditRowRoles(int i)
        {


            DropDownList idRolddl = ((DropDownList)formularioGridView.Rows[i].FindControl("accesoEditDropDownList"));
            TextBox idRol = ((TextBox)formularioGridView.Rows[i].FindControl("accesoEditTextBox"));
           
                idRolddl.DataSource = new ListValueBL().GetFormularioAcceso();
                idRolddl.DataBind();
            
            //monedaDropDownList.SelectedValue = monedaText.Text;
                idRolddl.SelectedValue = idRol.Text;


        }

        private void setEditFormListaRowRoles(int i)
        {


            DropDownList idRolddl = ((DropDownList)ListaGridView.Rows[i].FindControl("accesoEditDropDownList"));
            TextBox idRol = ((TextBox)ListaGridView.Rows[i].FindControl("accesoEditTextBox"));

            idRolddl.DataSource = new ListValueBL().GetFormularioAcceso();
            idRolddl.DataBind();

            //monedaDropDownList.SelectedValue = monedaText.Text;
            idRolddl.SelectedValue = idRol.Text;


        }
        //private void setFooterRowRoles()
        //{
        //    List<Rol> RolList = (List<Rol>)Session[rolesid.Value];

        //    DropDownList rolInsertDropDownList = ((DropDownList)rolesGridView.FooterRow.FindControl("rolInsertDropDownList"));

        //    rolInsertDropDownList.DataValueField = "idInternal";
        //    rolInsertDropDownList.DataTextField = "descripcion";
        //    rolInsertDropDownList.DataSource = RolList;
        //    rolInsertDropDownList.DataBind();


        //}

        //private void setFooterRowFormularios()
        //{
        //    var FormulariosList = DbUtil.Db.Menus;
        //    var AccesoList = DbUtil.Db.FormularioAcceso;

        //    DropDownList formularioInsertDropDownList = ((DropDownList)formularioGridView.FooterRow.FindControl("formularioInsertDropDownList"));
        //    DropDownList accesoInsertDropDownList = ((DropDownList)formularioGridView.FooterRow.FindControl("accesoInsertDropDownList"));


        //    formularioInsertDropDownList.DataValueField = "idInternal";
        //    formularioInsertDropDownList.DataTextField = "descripcion";
        //    formularioInsertDropDownList.DataSource = FormulariosList.ToList();
        //    formularioInsertDropDownList.DataBind();



        //    accesoInsertDropDownList.DataValueField = "idInternal";
        //    accesoInsertDropDownList.DataTextField = "descripcion";
        //    accesoInsertDropDownList.DataSource = AccesoList.ToList();
        //    accesoInsertDropDownList.DataBind();

        //}

        //private void setEditRowFormularios(int i)
        //{
        //    var FormulariosList = DbUtil.Db.Menus;
        //    var AccesoList = DbUtil.Db.FormularioAccesos;


        //    //DropDownList formularioInsertDropDownList = 
        //    //    ((DropDownList)formularioGridView.Rows[i].FindControl("formualrioEditDropDownList"));
        //    DropDownList accesoInsertDropDownList =
        //        ((DropDownList)formularioGridView.Rows[i].FindControl("accesoEditDropDownList"));
        //    //TextBox idobratxt = ((TextBox)formularioGridView.Rows[i].FindControl("idobratxt"));


        //    //formularioInsertDropDownList.DataValueField = "idInternal";
        //    //formularioInsertDropDownList.DataTextField = "descripcion";
        //    //formularioInsertDropDownList.DataSource = FormulariosList.ToList();
        //    //formularioInsertDropDownList.DataBind();



        //    accesoInsertDropDownList.DataValueField = "idInternal";
        //    accesoInsertDropDownList.DataTextField = "descripcion";
        //    accesoInsertDropDownList.DataSource = AccesoList.ToList();
        //    accesoInsertDropDownList.DataBind();
            
        //    //monedaDropDownList.SelectedValue = monedaText.Text;
        //    //obraDropDownList.SelectedValue = idobratxt.Text;


        //}
        protected void btnSaveContinue_Click(object sender, EventArgs e)
        {


            try
            {

                if (((Button)sender).Text == cancelarButton.Text)
                {
                    Response.Redirect("RolListForm.aspx?id=" + internalid.Value, false);

                }

                if (((Button)sender).Text == saveButton.Text)
                {

                    if (nivelComparativoDropDownList.SelectedValue != "2")
                    {
                        montoTextBox.Text = "-1";
                    }
                    if(montoTextBox.Text==String.Empty)
                            montoTextBox.Text="-1";
                    

                    DataSet EList = (DataSet)Session[idFormularioRolList.Value];


                    BOL.RolBL BL = new BOL.RolBL();

                    if (type.Value == "A")
                    {
                        internalid.Value = BL.add(descripcionTextBox.Text,
                            activoChk.Checked,
                            int.Parse(nivelPresupuestoDropDownList.SelectedValue),
                            int.Parse(nivelComparativoDropDownList.SelectedValue),
                            decimal.Parse(montoTextBox.Text),
                            AprobarOCCheckBox.Checked,
                            bitAprobarCheckBox.Checked,
                            bitVistoBuenoCajaChicachk.Checked,
                            bitDepositoCajaChicaCheckBox.Checked,
                            bitkardexCHK.Checked,
                            EList).ToString();
                    }
                    if (type.Value == "E")
                    {
                       BL.update(int.Parse(internalid.Value),
                            descripcionTextBox.Text,
                            activoChk.Checked,
                            int.Parse(nivelPresupuestoDropDownList.SelectedValue),
                            int.Parse(nivelComparativoDropDownList.SelectedValue),
                            decimal.Parse(montoTextBox.Text),
                            AprobarOCCheckBox.Checked,
                            bitAprobarCheckBox.Checked,
                            bitVistoBuenoCajaChicachk.Checked,
                            bitDepositoCajaChicaCheckBox.Checked,
                            bitkardexCHK.Checked,
                            EList).ToString();
                    }

                    if (int.Parse(internalid.Value)> 0)
                    {

                        Response.Redirect("~/Seguridad/rolReadForm.aspx?id=" + internalid.Value, false);
                    }
                }
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }


        protected void refreshButton_Click(object sender, EventArgs e)
        {
            formatForm();
        }

        protected void AddObraItem(object sender, EventArgs e)
        {
            try
            {

                DataSet empleadoObraList =    (DataSet)Session[idFormularioRolList.Value];

                DropDownList formularioDDL =
                    ((DropDownList)formularioGridView.FooterRow.FindControl("formularioInsertDropDownList"));

                DropDownList accesoDDL =
                    ((DropDownList)formularioGridView.FooterRow.FindControl("accesoInsertDropDownList"));


                foreach (DataRow a in empleadoObraList.Tables["rolFormularioListInfo"].Rows)
                {
                    if (a.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }
                    if (a.Field<int>("idFormulario") == int.Parse(formularioDDL.SelectedValue))
                    {

                        if (a.Field<int>("idAcceso") == int.Parse(formularioDDL.SelectedValue))
                        {
                            throw new Exception("Formulario y Acceso ya Ingresados");
                        }


                    }
                }



                DataRow item = empleadoObraList.Tables["rolFormularioListInfo"].NewRow();

                rolFormularioListInfo rol;
                
                item["idInternal"] = Parametros.GenerarID();
                item["idFormulario"] = int.Parse(formularioDDL.SelectedItem.Value);
                item["formulario"] = formularioDDL.SelectedItem.Text;
                item["idAcceso"] = int.Parse(accesoDDL.SelectedValue);
                item["Acceso"] = accesoDDL.SelectedItem.Text;
                //item["idRol"] = int.Parse(internalid.Value);

                empleadoObraList.Tables["rolFormularioListInfo"].Rows.Add(item);
                Session[idFormularioRolList.Value.ToString()] = empleadoObraList;
                DataBindFormularios();
                //setFooterRowFormularios();

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void DeleteObraItem(object sender, EventArgs e)
        {
            try
            {

                ImageButton lnkRemove = (ImageButton)sender;
                int idInternal = int.Parse(lnkRemove.CommandArgument.ToString());

                DataSet eRolList = (DataSet)Session[idFormularioRolList.Value];

                DataRow drw = eRolList.Tables["view_EmpleadoObra"].AsEnumerable().Where(p => p.RowState != DataRowState.Deleted).Single(p => p.Field<int>("idInternal") == idInternal);

                //eliminamos de la coleccion
                drw.Delete();
                //eRolList.Tables[1].Rows.Remove(drw);

                Session[idFormularioRolList.Value.ToString()] = eRolList;

                DataBindFormularios();
                //setFooterRowFormularios();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        protected void CancelItem(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                formularioGridView.EditIndex = -1;
                DataBindFormularios();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            try
            {
                formularioGridView.EditIndex = e.NewEditIndex;
                DataBindFormularios();
                setEditRowRoles(e.NewEditIndex);
                formularioGridView.FooterRow.Visible = false;
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);
                //DropDownList formularioDDL =
                //    (DropDownList)gv.Rows[e.RowIndex].FindControl("formualrioEditDropDownList");
                DropDownList accesoDDL =
                    ((DropDownList)gv.Rows[e.RowIndex].FindControl("accesoEditDropDownList"));
                


                int idinternal = int.Parse(gv.DataKeys[e.RowIndex].Values[0].ToString());


                DataSet itemList = (DataSet)Session[idFormularioRolList.Value];

                var item = itemList.Tables["rolFormularioListInfo"].AsEnumerable().Where(p => p.RowState != DataRowState.Deleted)
                .Single(p => p.Field<int>("idInternal") == idinternal);

                //item["idInternal"] = Parametros.GenerarID();
                //item["idFormulario"] = int.Parse(formularioDDL.SelectedItem.Value);
                //item["formulario"] = formularioDDL.SelectedItem.Text;
                item["idAcceso"] = int.Parse(accesoDDL.SelectedValue);
                item["Acceso"] = accesoDDL.SelectedItem.Text;



                Session[idFormularioRolList.Value.ToString()] = itemList;

                gv.EditIndex = -1;

               
                DataBindFormularios();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }




        protected void CancelListaItem(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                ListaGridView.EditIndex = -1;
                DataBindFormulariosListas();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void EditListaItem(object sender, GridViewEditEventArgs e)
        {
            try
            {
                ListaGridView.EditIndex = e.NewEditIndex;
                DataBindFormulariosListas();
                setEditFormListaRowRoles(e.NewEditIndex);
                ListaGridView.FooterRow.Visible = false;
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void UpdateListaItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);
                //DropDownList formularioDDL =
                //    (DropDownList)gv.Rows[e.RowIndex].FindControl("formualrioEditDropDownList");
                DropDownList accesoDDL =
                    ((DropDownList)gv.Rows[e.RowIndex].FindControl("accesoEditDropDownList"));



                int idinternal = int.Parse(gv.DataKeys[e.RowIndex].Values[0].ToString());


                DataSet itemList = (DataSet)Session[idFormularioRolList.Value];

                var item = itemList.Tables["rolFormularioListInfo2"].AsEnumerable().Where(p => p.RowState != DataRowState.Deleted)
                .Single(p => p.Field<int>("idInternal") == idinternal);

                //item["idInternal"] = Parametros.GenerarID();
                //item["idFormulario"] = int.Parse(formularioDDL.SelectedItem.Value);
                //item["formulario"] = formularioDDL.SelectedItem.Text;
                item["idAcceso"] = int.Parse(accesoDDL.SelectedValue);
                item["Acceso"] = accesoDDL.SelectedItem.Text;



                Session[idFormularioRolList.Value.ToString()] = itemList;

                gv.EditIndex = -1;


                DataBindFormulariosListas();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }






        private void validacom2()
        {
            if (nivelComparativoDropDownList.SelectedValue == "2")
            {
                montoTextBox.Visible = true;
                simbolLabel.Visible = true;

            }
            else
            {
                montoTextBox.Visible = false;
                simbolLabel.Visible = false;

            }
            nivelCompUpdatePanel.Update();
        }
        protected void nivelComparativoDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            validacom2();

           
        }
    }
}